package com.park.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.park.dao.AreaDAO;
import com.park.dao.AuthorityDAO;
import com.park.dao.StreetDAO;
import com.park.dao.ZTreeDAO;
import com.park.dao.ZonecenterDAO;
import com.park.model.AuthUser;
import com.park.model.Zonecenter;
import com.park.model.ZtreeShiQuLuDuan;
import com.park.service.ZTreeService;

@Service
public class ZTreeServiceImpl implements ZTreeService {
	@Autowired
	private ZonecenterDAO zoneCenterDao;
	@Autowired
	private AreaDAO areaDao;
	@Autowired
	private StreetDAO streetDao;
	@Autowired
	private ZTreeDAO ztreeDao;
	@Autowired
	private AuthorityDAO userDao;

	@SuppressWarnings("unlikely-arg-type")
	@Override
	public List<ZtreeShiQuLuDuan> getTree(String username) {
		System.out.println(username);
		AuthUser user = userDao.getUser(username);
		List<Map<Object, Object>> zonecenters = new ArrayList<>();
		System.out.println(user);
		if(user.getRole() == 0) {
			zonecenters = ztreeDao.getAllCenter();
		}else {
			zonecenters = ztreeDao.getByUserName(username);
		}
		Object parentId = null;
		Object parentId1 = null;
		List<ZtreeShiQuLuDuan> zTrees = new ArrayList<>();
		for(Map<Object, Object> entry : zonecenters) {
			ZtreeShiQuLuDuan ztrees = new ZtreeShiQuLuDuan();
			parentId = entry.get("id");
			ztrees.setValue(parentId);
			ztrees.setLabel(entry.get("name"));
			ztrees.setParentId(null);
			List<Map<Object,Object>> areas = ztreeDao.getByCenterId(entry.get("id"));
			ZtreeShiQuLuDuan areaTree = new ZtreeShiQuLuDuan();
			List<ZtreeShiQuLuDuan> areaTrees = new ArrayList<>();
			for(Map<Object, Object> entryArea : areas) {
				parentId1 = entryArea.get("id");
				areaTree.setValue(parentId1);
				areaTree.setLabel(entryArea.get("name"));
				areaTree.setParentId(parentId);
				ztrees.setParentId(null);
				List<Map<Object, Object>> street = ztreeDao.getByAreaId(entryArea.get("id"));
				List<ZtreeShiQuLuDuan> streetTrees = new ArrayList<>();
				for(Map<Object, Object> entryStreet : street) {
					ZtreeShiQuLuDuan streetTree = new ZtreeShiQuLuDuan();
					streetTree.setValue(entryStreet.get("id"));
					streetTree.setLabel(entryStreet.get("name"));
					streetTree.setParentId(parentId1);
					streetTrees.add(streetTree);
				}
				areaTree.setChildren(streetTrees);
				areaTrees.add(areaTree);
			}
			ztrees.setChildren(areaTrees);
			zTrees.add(ztrees);
		}
		return zTrees;
	}

}
